package com.wisewin.pose.api.interceptor;

import com.wisewin.pose.util.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthenticationInterceptor implements HandlerInterceptor {

    final static Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Value("${spring.profiles.active}")
    private String active;

    private static final IpUtil ipUtil = new IpUtil();

//    @Autowired
//    private RedisUtil redis;

//    @Autowired
//    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 打印请求相关参数
        logger.info("========================= Start ======================");
        // 打印请求 url
        logger.info("URL         : {}", httpServletRequest.getRequestURL().toString());
        // 打印 Http method
        logger.info("HTTP Method : {}", httpServletRequest.getMethod());
        // 打印请求的 IP
        logger.info("IP          : {}", ipUtil.getIpAddr(httpServletRequest));
//        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
//        if(!(object instanceof HandlerMethod)){
//            return true;
//        }
//        HandlerMethod handlerMethod=(HandlerMethod)object;
//        Method method=handlerMethod.getMethod();
//        //检查是否有passToken注释，有则跳过认证
//        if (method.isAnnotationPresent(PassToken.class)) {
//            PassToken passToken = method.getAnnotation(PassToken.class);
//            if (passToken.required()) {
//                return true;
//            }
//        }
//        //检查安全请求认证
//        if ("prod".equals(active)){
//            String safeRequestToken = httpServletRequest.getHeader("safeRequestToken");
//            if(!"ZA_krzDSN1r_fNw94F2437hRgj9a-taCHaNU36TDoxY".equals(safeRequestToken)){
//                throw new LoginException("安全请求认证失败");
//            }
//        }
//        //检查所属项目参数
//        String project = httpServletRequest.getHeader("project");
//        logger.info("project     : {}", project);
//        //检查平台参数
//        String platForm = httpServletRequest.getHeader("platForm");
//        logger.info("platForm    : {}", platForm);
//        //检查有没有需要用户登录的注解
//        if (method.isAnnotationPresent(UserLoginToken.class)) {
//            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
//            if (userLoginToken.required()) {
//                // 执行认证
//                if (token == null) {
//                    throw new LoginException("无有效token，请重新登录");
//                }
//                // 获取 token 中的account
//                String account = "-1";
//                try {
//                    account = JWT.decode(token).getAudience().get(0);
//                }catch (Exception e){
//
//                }
//                //从redis中获取token ip信息进行验证
//                if(Constants.nursery.getValue().equals(project)){
//                    Object objectMap = redis.get("loginNurseryUser"+account);
//                    if (objectMap == null||account.equals("-1")) {
//                        throw new LoginException("登录已过期，请重新登录");
//                    }
//                    logger.info("登录用户手机号: {}", account);
//                }else{
//                    Object objectMap = redis.get("loginUser"+account);
//                    if (objectMap == null||account.equals("-1")) {
//                        throw new LoginException("登录已过期，请重新登录");
//                    }
//                    Map<String,String> redisMap = (Map<String,String>)objectMap;
//                    String redisIp = redisMap.get("ip");
//                    String curIp = ipUtil.getIpAddr(httpServletRequest);
//                    logger.info("redisIp     : {}", redisIp);
//                    logger.info("curIp       : {}", curIp);
//                    logger.info("登录用户手机号: {}", account);
//                    //每操作一次，从新往redis中存一次刷新时间
//                    redis.set(account, objectMap, 60 * 60 * 24 * 7);
//                }
//                //更新用户使用平台
//                userService.updateUserUsePlatform(account,platForm);
//            }
//        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("========================= End ======================");
    }
}
